<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/5/29
 * Time: 14:29
 */

namespace Home\Service;


use Common\Common\Service;
use Home\Component\ActComponent;
use Home\Component\UserComponent;
use Home\Exception\HomeException;
use Home\Request\User\CheckDayNumRequest;
use Home\Response\CheckApplyResponse;

class CheckDayNumService implements Service
{
    public function run(CheckDayNumRequest $request = null)
    {
        if ($request->issetUserId() == false)
            throw new HomeException(10001);
        if ($request->verifyUserId() == false)
            throw new HomeException(10002);
        if ($request->IsUserIdInRange() == false)
            throw new HomeException(10003);
        if ($request->issetActId() == false)
            throw new HomeException(10001);
        if ($request->verifyActId() == false)
            throw new HomeException(10002);
        if ($request->IsActIdInRange() == false)
            throw new HomeException(10003);

        $user_id = $request->getUserId();
        $act_id = $request->getActId();
        $component = new UserComponent();
        $response = new CheckApplyResponse();

        try {
            $data = $component->findDayNum($user_id);
            if (is_null($data) == true) {
                $response->setItIsNull();
            } else {
                $day_num = $data['day_num'];
                $last_time = strtotime($data['last_time']);
                $last_day = date('Y-m-d', $last_time);
                $day = date('Y-m-d');
                //判断今天是否投票过
                if ($day == $last_day) {
                    //若今天投票过，判断用户今天投票数是否超过限制
                    $component = new ActComponent();
                    $data = $component->getActDayNum($act_id);
                    if (is_null($data) == false) {
                        if ($day_num >= $data['day_vote_num']) {
                            //若用户超过限制，不准投票
                            //$response->setFlag();
                            throw new HomeException(30012);
                        }
                    }
                } else {
                    //若今天没有投票过，将用户今天票数设为1，修改最后投票时间
                    $time = date('Y-m-d H:i:s');
                    $component->resetDayNum($user_id);
                    $component->saveTime($time, $user_id);
                    $response->setFlag();
                }
                //  $response->setData($data);
            }
        } catch (HomeException $e) {
            throw new HomeException($e->getMessage(), $e->getCode());
        }
        return $response;
    }
}